package com.zzyl.nursing.service.impl;


import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.*;
import com.zzyl.nursing.vo.health.HealthMassgeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-26
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private DeviceDataMapper deviceDataMapper;


    @Autowired
    private IoTDAClient client;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    /**
     * 小程序端登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //获取openid  微信接口获取
        String openid = wechatService.getOpenid(dto.getCode());

        //根据openid查询用户信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openid));

        //如果用户为空，构建用户，赋值一个openid
        if (ObjectUtil.isEmpty(familyMember)) {
            familyMember = FamilyMember
                    .builder()
                    .openId(openid)
                    .build();
        }

        //获取用户的手机号  微信接口获取
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //保存或更新用户
        insertOrUpdateFamilyMember(familyMember, phone);

        //生成token返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("userName", familyMember.getName());

        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(familyMember.getName());
        loginVo.setToken(token);

        return loginVo;
    }

    /**
     * 保存或更新用户
     *
     * @param familyMember
     * @param phone
     */
    private void insertOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //判断手机号与数据库的手机号是否一致
        if (ObjectUtil.notEqual(familyMember.getPhone(), phone)) {
            familyMember.setPhone(phone);
        }
        //判断是否存在id，如果存在id，则更新，不存在则保存
        if (ObjectUtil.isNotEmpty(familyMember.getId())) {
            updateById(familyMember);
            return;
        }
        //获取用户的昵称
        int index = (int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size());
        String nickName = DEFAULT_NICKNAME_PREFIX.get(index) + StringUtils.substring(phone, 7, 11);
        familyMember.setName(nickName);
        //保存
        save(familyMember);

    }


    @Override
    @Transactional
    public void add(ElderFamilyDto elderFamilyDto) {
        //获取到姓名和省份证号
        String name = elderFamilyDto.getName();
        String idCard = elderFamilyDto.getIdCard();

        //到老人表中查询是否存在该老人
        Elder elder = elderMapper.selectElderByNmmeAndIdCard(name, idCard);
        if (ObjectUtil.isEmpty(elder)) {
            throw new BaseException("没有该老人");
        }

        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        //获取当前用户的id
        Long userId = UserThreadLocal.getUserId();
        familyMemberElder.setFamilyMemberId(userId);
        familyMemberElder.setElderId(elder.getId());
        familyMemberElder.setCreateTime(new Date());


        //保存到表中
        familyMemberElderMapper.insert(familyMemberElder);
    }

    /**
     * 获取老人家属
     */
    @Override
    public List<FamilyMemberElderVo> my() {
        //获取当前用户id
        Long userId = UserThreadLocal.getUserId();
        return familyMemberElderMapper.my(userId);
    }

    /**
     * 分页查询老人家属
     */
    @Override
    public List<FamilyMemberPageVo> listByPage(Integer pageNum, Integer pageSize) {
        Long userId = UserThreadLocal.getUserId();
        return familyMemberElderMapper.listByPage(userId);
    }

    /**
     * 删除家人
     */
    @Override
    public AjaxResult deleteById(Long id) {
        familyMemberElderMapper.deleteById(id);
        return AjaxResult.success();
    }


    /**
     * 查询设备数据
     */
    @Override
    public HealthMassgeVo queryDevicePropertyStatus(String deviceName, String productKey) {

        //查询设备是否存在
        DeviceInfo deviceInfo = deviceMapper.queryDeviceInfoByDeviceName(deviceName, productKey);
        if (deviceInfo == null) {
            throw new BaseException("设备不存在");
        }

        //获取设备ID
        String iotId = deviceInfo.getIotId();
        //获取设备的最新数据
        Object status = redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, iotId);
        if (status == null) {
            throw new BaseException("设备数据不存在");
        }

        String jsonStr = status.toString();
        //创建集合
        List<PropertyStatusInfo> propertyStatusInfos = new ArrayList<>();
        List<Object> dataList = JSONUtil.toList(jsonStr, Object.class);
        // 遍历循环赋值
        for (Object item : dataList) {
            /**
             * 将JSON对象转换为PropertyStatusInfo实体对象
             * @param item 待解析的JSON字符串或对象
             * @return 解析后的PropertyStatusInfo对象
             */
            cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(item);
            PropertyStatusInfo propertyStatusInfo = new PropertyStatusInfo();

            // 设置 dataType
            propertyStatusInfo.setDataType("double");
            // 设置 identifier（functionId）
            propertyStatusInfo.setIdentifier(jsonObject.getStr("functionId"));
            //获取到identifier
            String identifier = propertyStatusInfo.getIdentifier();
            // 设置 name（deviceName）
            if (identifier.equals("xueyang")) {
                propertyStatusInfo.setName("血氧");
            } else if (identifier.equals("HeartRate")) {
                propertyStatusInfo.setName("心率");
            } else if (identifier.equals("BodyTemp")) {
                propertyStatusInfo.setName("体温");
            } else if (identifier.equals("BatteryPercentage")) {
                propertyStatusInfo.setName("用电量");
            } else {
                propertyStatusInfo.setName(jsonObject.getStr("deviceName"));
            }

            // 设置 time（createTime）
            String createTimeStr = jsonObject.getStr("createTime");
            if (createTimeStr != null && !createTimeStr.isEmpty()) {
                propertyStatusInfo.setTime(createTimeStr);
            }
            // 设置 value（dataValue）
            Object dataValue = jsonObject.get("dataValue");
            if (dataValue != null) {
                propertyStatusInfo.setValue((String) dataValue);
            }
            // 设置 unit
            propertyStatusInfo.setUnit("double");
            propertyStatusInfos.add(propertyStatusInfo);
        }
        HealthMassgeVo healthMessgeVo = new HealthMassgeVo();
        healthMessgeVo.setPropertyStatusInfo(propertyStatusInfos);
        return healthMessgeVo;
    }

    /**
     * 按天统计查询指标数据
     */

    @Override
    public List<HourlyDataVo> queryDeviceDataListByDay(String iotId, Long startTime, Long endTime, String functionId) {
        //将开始时间和结束时间进行解析
        LocalDateTime startDateTime = LocalDateTimeUtil.of(startTime);
        LocalDateTime endDateTime = LocalDateTimeUtil.of(endTime);

        return deviceDataMapper.queryDeviceDataListByDay(iotId, functionId, startDateTime, endDateTime);
    }

    /**
     * 按周查询设备数据
     */
    @Override
    public List<HourlyDataVo> queryDeviceDataListByWeek(String iotId, Long startTime, Long endTime, String functionId) {
        //将开始时间和结束时间进行解析
        LocalDateTime startDateTime = LocalDateTimeUtil.of(startTime);
        LocalDateTime endDateTime = LocalDateTimeUtil.of(endTime);

        return deviceDataMapper.queryDeviceDataListByWeek(iotId, functionId, startDateTime, endDateTime);
    }
}
